from django.conf import settings
from django.contrib.auth import login, logout, authenticate
from django.shortcuts import render, redirect, reverse
from django.views import View

from .form import RegisterForm

from utils.response import ApiResponse, Code


class RegisterView(View):
    def get(self, request):
        return render(request, 'test.html')

    def post(self, request):
        form = RegisterForm(data=request.POST)
        if form.is_valid():
            form.save()
            return ApiResponse(msg="注册成功~~")
        return ApiResponse(code=Code.Bad, msg='<br>'.join(form.get_errors()))


class LoginView(View):
    def get(self, request):
        return render(request, 'test.html')

    def post(self, request):
        account = request.POST.get('account')
        password = request.POST.get('password')
        instance = authenticate(account=account, password=password)
        if instance:
            login(request, instance)
            return ApiResponse(msg="登录成功~~")
        return ApiResponse(code=Code.Bad, msg='账号或密码错误~~')


def logout_view(request):
    logout(request)
    return redirect(reverse("/"))
